package com.ruoyi.web.controller.tool;

import com.ruoyi.common.core.domain.AjaxResult;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Component
public class UrlProcessor {
    private static final Logger log = LoggerFactory.getLogger(UrlProcessor.class);
    private final RestTemplate restTemplate;

    public UrlProcessor() {
        this.restTemplate = new RestTemplate();
    }

    /**
     * 处理Excel文件并生成URL内容描述
     *
     * @param file Excel文件
     * @param urlColumnIndex URL所在列的索引（从0开始）
     * @return 处理结果
     */
    public AjaxResult processUrls(MultipartFile file, int urlColumnIndex) {
        try {
            List<String> descriptions = new ArrayList<>();
            List<String> urls = readUrlsFromExcel(file, urlColumnIndex);

            for (String url : urls) {
                try {
                    String content = fetchUrlContent(url);
                    String description = generateDescription(content);
                    descriptions.add("URL: " + url + "\n描述: " + description);
                } catch (Exception e) {
                    log.error("处理URL时出错: " + url, e);
                    descriptions.add("URL: " + url + "\n处理失败: " + e.getMessage());
                }
            }

            return AjaxResult.success("处理完成", descriptions);
        } catch (Exception e) {
            log.error("处理Excel文件时出错", e);
            return AjaxResult.error("处理Excel文件时出错: " + e.getMessage());
        }
    }

    /**
     * 从Excel文件中读取URL列表
     */
    private List<String> readUrlsFromExcel(MultipartFile file, int urlColumnIndex) throws IOException {
        List<String> urls = new ArrayList<>();
        try (InputStream is = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(is)) {

            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                Cell cell = row.getCell(urlColumnIndex);
                if (cell != null && cell.getCellType() == CellType.STRING) {
                    String url = cell.getStringCellValue().trim();
                    if (!url.isEmpty()) {
                        urls.add(url);
                    }
                }
            }
        }
        return urls;
    }

    /**
     * 获取URL内容
     */
    private String fetchUrlContent(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_HTML);
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");

        ResponseEntity<String> response = restTemplate.exchange(
            url,
            HttpMethod.GET,
            new HttpEntity<>(headers),
            String.class
        );

        return response.getBody();
    }

    /**
     * 根据页面内容生成描述
     * 注意：这里是一个简单的示例，实际项目中您可能需要集成更专业的AI服务
     */
    private String generateDescription(String content) {
        // 这里是一个简单的实现示例
        // 实际使用时，您可以：
        // 1. 调用OpenAI API
        // 2. 使用本地部署的AI模型
        // 3. 调用其他AI服务提供商的API

        // 简单示例：提取页面标题
        String title = extractTitle(content);
        return "这是一个关于 " + (title.isEmpty() ? "未知主题" : title) + " 的网页";
    }

    /**
     * 从HTML内容中提取标题
     */
    private String extractTitle(String content) {
        if (content == null || content.isEmpty()) {
            return "";
        }

        int titleStart = content.toLowerCase().indexOf("<title>");
        int titleEnd = content.toLowerCase().indexOf("</title>");

        if (titleStart >= 0 && titleEnd > titleStart) {
            return content.substring(titleStart + 7, titleEnd).trim();
        }

        return "";
    }
}
